package com.globallogic.socialnetwork.jsf.bean;

import java.io.File;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;

import com.globallogic.socialnetwork.entity.User;
import com.globallogic.socialnetwork.service.UserService;
import com.globallogic.socialnetwork.util.Constants;
import com.globallogic.socialnetwork.util.DaoException;
import com.globallogic.socialnetwork.util.WebApplication;

/**
 * JSF Bean to handle all functions associated with any user
 */
@Named("userBean")
@Scope("session")
public class UserBean implements Constants {

	@Inject
	@Named("userService")
	private UserService userService;
	private User user;
	private String avatarPath;
	private List<User> friends;
	private final static Logger log = Logger.getLogger("SocialNetworkFileLogger");

	public UserBean(User user) {
		this.user = user;
		avatarPath = getAvatar();
	}

	public UserBean() {
	}

	/**
	 * 
	 * @return avatar's path
	 */
	private String getAvatar() {
		if (checkAvatar() != null)
			return checkAvatar().replaceFirst("/webapps", "");
		else
			return defaultAvatar.replaceFirst("/webapps", "");
	}

	/**
	 * Checks if avatar's path exist
	 * 
	 * @return avatar's path if exists or null if doesn't
	 */
	private String checkAvatar() {
		for (int i = 0; i < extensions.length; i++) {
			String avatarPath = dirWebImgAvatars + user.getLogin()
					+ extensions[i].toString();
			if (new File(avatarPath).exists())
				return avatarPath;
		}
		return null;
	}

	/**
	 * Gets user's name as parameter from client side and returns user
	 * 
	 * @return user
	 */
	public User getUser() {
		try {
			if (WebApplication.isParameter("user")) {
				String friendLogin = WebApplication.getParameter("user")
						.toString();
				user = userService.getUser(friendLogin);
			}
		} catch (DaoException e) {
			log.warn(e);
		}
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getAvatarPath() {
		avatarPath = getAvatar();
		return avatarPath;
	}

	public void setAvatarPath(String avatarPath) {
		this.avatarPath = avatarPath;
	}

	public List<User> getFriends() {
		try {
			if (WebApplication.isParameter("user")) {
				String friendLogin = WebApplication.getParameter("user")
						.toString();
				friends = userService.getFriends(friendLogin);
			}
		} catch (DaoException e) {
			log.warn(e);
		}
		return friends;
	}

	public void setFriends(List<User> friends) {
		this.friends = friends;
	}

}
